package cn.cas.mango.dto.param;

import cn.cas.mango.util.string.StringUtils;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOptions;
import co.elastic.clients.elasticsearch._types.SortOrder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * material搜索的传入参数
 */
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MaterialParam extends BaseParam{
  private String startDate;
  private String endDate;
  private String date;
  private Integer currentPage;
  private Integer pageSize;
  private String queryStr;
  private String materialFor;
  private String materialSources;
  private String materialTypes;
  private String queryField;
  //
  private String searchType;
  private String security;
  private String sortOrder;
  private String sortType;
  private String uid;
  private String id;
  private Double degree;
  private Integer department;
  // 查询的唯一标识
  private String uuid;

  private List<FieldValue> materialTypesArray;
  private List<FieldValue> securityArray;
  private List<FieldValue> uidArray;


  public static MaterialParam getFromFormData(Map<String, Object> errMessage) {
    MaterialParam materialParam = (MaterialParam) errMessage.get("formData");
    // 把中文符号转为英文
    materialParam.setQueryStr(
      StringUtils.preprocessString(materialParam.getQueryStr())
    );
    return materialParam;
  }

  /**
   * @return 由 order sortField SortOptions 组成的列表
   */
  public List<Object> get3Sorts() {
    SortOrder order;
    String sortField;

    switch (this.getSortOrder().toLowerCase()) {
      case "asc":
        order = SortOrder.Asc;
        break;
      case "desc":
        order = SortOrder.Desc;
        break;
      default:
        throw new IllegalArgumentException("sortOrder:"+this.getSortOrder()+"暂不支持，目前仅支持desc和asc");
    }

    switch (this.getSortType().toLowerCase()) {
      case "time":
        // TODO 确认下是否使用该字段
        sortField = "material_time";
        break;
      case "sim":
        sortField = "_score";
        break;
      default:
        throw new IllegalArgumentException("sortType:"+this.getSortType()+"暂不支持，目前仅支持sim和time");
    }

    SortOptions sortOptions = SortOptions.of(
      s -> s.field(f -> f.field(sortField).order(order)));
    return new ArrayList<Object>(){{add(order);add(sortField); add(sortOptions);}};
  }
}
